import { decrypt } from "@/utils/crypto";
import Cookies from 'js-cookie';
import { RouteRecordRaw, createRouter, createWebHistory } from "vue-router";
import manage from './manage';
const routes: RouteRecordRaw[] = [
    {
        name: '',
        path: '/',
        component: () => import('@/components/layout.vue'),
        redirect: '/create',
        children: [
            {
                name: 'create',
                path: '/create',
                component: () => import('@/pages/chats/create.vue')
            },
            {
                name: 'chat',
                path: '/chat/:id',
                props: true,
                component: () => import('@/pages/chats/index.vue')
            },
            {
                name: 'setting',
                path: '/setting',
                component: () => import('@/pages/setting/index.vue'),
            },
            {
                name: 'help',
                path: '/help',
                component: () => import('@/pages/help/index.vue'),
            },
            {
                name: 'tags',
                path: '/tags',
                component: () => import('@/pages/tag/index.vue'),
            },
            {
                name: 'subscription',
                path: '/subscription',
                component: () => import('@/pages/subscription/index.vue'),
            }
        ]
    }, {
        name: 'login',
        path: '/login',
        component: () => import('@/pages/login/index.vue'),
    }
]


const route = createRouter({
    history: createWebHistory(''),
    routes,
    scrollBehavior() {
        return ({ top: 0 })
    }
})

route.beforeEach((to, from, next) => {
    if (to.path == "/login") {
        next()
    }
    if (Cookies.get('info')) {  //如果用户已经登录
        next()
    } else {
        if (to.path == "/login") {  //如果用户已经登录且跳转前往登录页面
            next()
        } else {  //如果用户跳转的是其他页面则判断其是否拥有权限
            next({ name: "login" })
        }
    }
})
if (Cookies.get('info')) {
    if (JSON.parse(decrypt(Cookies.get("info"))).admin) {
        route.addRoute(manage)
    }
}

export default route